#include <vector>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    TreeNode* _build(vector<int>& inorder, vector<int>& postorder,
                     int& posti, int inbegin, int inend)
    {
        if(inbegin > inend)
            return nullptr;
        TreeNode* root = new TreeNode(postorder[posti]);
        int ini = inbegin;
        while(ini <= inend)
        {
            if(inorder[ini] == postorder[posti])
                break;
            ini++;
        }
        posti--;
        root->right = _build(inorder, postorder, posti, ini+1, inend);
        root->left = _build(inorder, postorder, posti, inbegin, ini-1);
        return root;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
    {
        int i = postorder.size()-1;
        return _build(inorder, postorder, i, 0, inorder.size()-1);
    }
};
